console.log('tax injected');
import { transformDataByOpenWeb } from './../../lib/openWebTransform.js';
import { generateImg } from './../../lib/zeroReportUtils.js';
import { syncReportInfoHelper, fileUploadHelper } from './help.js';
import { startZeroReport, checkZeroReport } from './zeroReport.js';
// import { hsqjSmall } from './data/hsqj-small-json.js';
// import { hsqjInputJson } from './data/hsqj-json.js';
import { getinputData } from './data/xqykjzz.js';
import {
  startAsyncTableDetail,
  asyncTableDetail,
  asyncTableDetailFjs,
  asyncTableDetailFjsTable,
  asyncOpenPage
} from './asyncTable.js';
import { logout, openFakeWin } from './tool.js';

import './chongqing-invoice.js';

window.onbeforeunload = null;
const names = {
  profit: {
    name: '《利润表_月报（适用执行小企业会计准则的企业）》',
    code: 'lrbxxForm_'
  },
  balance: {
    name: '《资产负债表（适用执行小企业会计准则的企业）》',
    code: 'zcfzbxxForm_'
  },
  cash: {
    name: '《现金流量表_月报（适用执行小企业会计准则的企业）》',
    code: 'xjllbxxForm_'
  }
};
let namesKeys = [
  '《利润表_月报（适用执行小企业会计准则的企业）》', '《资产负债表（适用执行小企业会计准则的企业）》', '《现金流量表_月报（适用执行小企业会计准则的企业）》'
];
let isOnload = true;

let baseInfoCache;
let $iframe;

const readyCallback = () => {
  if (window.location.search.includes('isEnd=true')) {
    setTimeout(() => {
      logout();
    }, 1000);
  } else {
    window.postMessage(
      {
        event: 'getZeroInfo'
      },
      '*'
    );
    checkZeroReport();  
  }
};
try {
  if ($ && $.ready) {
    $(() => {
      readyCallback();
    });
  } else {
    setTimeout(readyCallback(), 2000);
  }
} catch (e) {
  console.log(window.location.href);
}

setTimeout(() => {
  if (isOnload) {
    isOnload = false;
    window.postMessage(
      {
        event: 'getBaseInfo'
      },
      '*'
    );
  }
}, 3000);
// if(window.location.href.includes('https://etax.chongqing.chinatax.gov.cn:6001/sword?ctrl=SB702SbdyCtrl_openByPzxh')) {
//   let embed = document.querySelector("body > embed");
//   console.log(embed);
//   setTimeout(() => {
//     let data = generateImg(embed);
//   }, 1000);
// }


window.onload = function () {
  console.log('loaded');
  isOnload = false;
  if (/^\/$/g.test(window.location.pathname)) {
    if (window.location.search.includes('isEnd=true')) {
      setTimeout(() => {
        logout();
      }, 1000);
    } else {
      window.postMessage(
        {
          event: 'getBaseInfo'
        },
        '*'
      );
    }
  }

  // 按期应申报界面
  if (
    /WLSB\/WLSBBS\/TTAX_index.html\?MODULE=TTAX_SB_JCSB.html/g.test(
      window.location.href
    )
  ) {
    setTimeout(function () {
      syncReportInfoHelper.captureDataFromPage();
    }, 2000);
  }

  // 尝试获取申报周期和申报报表类型
  if (/\/WLSB\/WLSBBS\/TTAX_index\.html/g.test(window.location.pathname)) {
    $('#indexContent').on('load', function () {
      let urlObj = url2json($(this).attr('src'));
      if (urlObj) {
        let urlQuery = urlObj;
        if (urlQuery.SZMC && urlQuery.SBSQ) {
          let SBSQ = urlQuery.SBSQ.split('-');
          let startTime = SBSQ[0].replace(/(\d{4})/g, '$1-');
          let endTime = SBSQ[1].replace(/(\d{4})/g, '$1-');
          let type;

          if (urlQuery.SZMC === '财务报表') {
            type = 'balance';
            setTimeout(function () {
              $('#indexContent')
                .contents()
                .find('tr[id^=datagrid-row-r2-2]')
                .dblclick(function (e) {
                  let curName = $(this).find('td[field=BB_MC]').text();
                  if (curName.search('利润表') > -1) {
                    type = 'profit';
                  } else if (curName.search('现金流量表') > -1) {
                    type = 'cash';
                  } else {
                    type = 'balance';
                  }
                  window.postMessage(
                    {
                      event: 'setPeriodAndType',
                      data: {
                        type: type,
                        startTime: startTime,
                        endTime: endTime
                      }
                    },
                    '*'
                  );
                });
            }, 1000);
          }

          window.postMessage(
            {
              event: 'setPeriodAndType',
              data: {
                type: type,
                startTime: startTime,
                endTime: endTime
              }
            },
            '*'
          );
        }
      }
    });
  }

  if (
    /\/sb_sdsA_yj_new\/sb_sdsA_yj_new\.html/g.test(window.location.pathname)
  ) {
    window.postMessage(
      {
        event: 'setPeriodAndType',
        data: {
          type: 'sds',
          startTime: $('.sssqq').eq(0).text().substr(0, 7),
          endTime: $('.sssqz').eq(0).text().substr(0, 7)
        }
      },
      '*'
    );
  }
};
function changeType() {
  const typeSign = $iframe.querySelector('input[name=SwordTreeJSON]');
  // sendInfo('《资产负债表（适用执行小企业会计准则的企业）》', typeSign);
  if (typeSign) {
    const MutationObserver = window.MutationObserver
      || window.WebKitMutationObserver
      || window.MozMutationObserver;
    const config = { attributes: true };
    let inputChange = new MutationObserver((records) => {
      records.find((item) => {
        if (item.attributeName === 'originvalue') {
          if (
            typeSign.getAttribute
            && typeSign.getAttribute('originvalue')
            && namesKeys.includes(typeSign.getAttribute('originvalue'))
          ) {
            const checkType = typeSign.getAttribute('originvalue')
              || '《资产负债表（适用执行小企业会计准则的企业）》';
            sendInfo(checkType, typeSign);
            return true;
          }
        }
        return false;
      });
    });
    inputChange.observe(typeSign, config);
  }
}

// 更新报表信息
function sendInfo(taxTypes, typeSign) {
  let info = {
    type: ''
  };
  let currentIframe = $iframe;
  Object.entries(names).map((item) => {
    if (item[1].name === taxTypes) {
      info.type = item[0];
    }
    return true;
  });
  if (!info.type) {
    alert('暂不支持改报表的一键报税！');
    return false;
  }
  if (info.type !== 'balance') {
    currentIframe = $iframe.getElementById(
      `table${typeSign.getAttribute('realvalue')}iframe`
    ).contentDocument;
  }

  // eslint-disable-next-line newline-per-chained-call
  info.startTime = document
    .querySelector('input[name=ssqq]')
    .getAttribute('realvalue')
    .split('-')
    .slice(0, 2)
    .join('-');
  // eslint-disable-next-line newline-per-chained-call
  info.endTime = document
    .querySelector('input[name=ssqz]')
    .getAttribute('realvalue')
    .split('-')
    .slice(0, 2)
    .join('-');
  window.postMessage(
    {
      event: 'setPeriodAndType',
      data: {
        ...info
      }
    },
    '*'
  );
}

window.addEventListener(
  'message',
  async function ({ data }) {
    // 只监听来自于content script的信息
    if (data.sender !== 'content-script') {
      return false;
    }
    if (data.event === 'setSaasData') {
      data = data.data;
      let sheet = data.saasData.sheet;
      if (sheet == 'sds' || sheet == 'zzs') {
        fillInput(data, sheet);
      } else if (sheet.includes('hsqj')) {
        fillHspj(await transformDataByOpenWeb(data), sheet);
        return true;
      } else {
        // fillInput(await transformDataByOpenWeb(data), sheet);
        newFillInput(data, sheet);
      }
    }
    if (data.event === 'getNationData') {
      getNationData(data.data.taxType);
    }
    if (data.event === 'getBaseInfo') {
      baseInfoCache = data.data;
      autoInputAccount(baseInfoCache);
    }
    // 同步申报表种类
    if (data.event === 'syncReportInfo') {
      syncReportInfoHelper.startGetReportInfo();
    }
    // 同步申报表
    if (data.event === 'syncReport') {
      await syncReportInfoHelper.startGetReport();
    }
    if (data.event === 'getZeroInfoBack') {
      if (!data.data.currentZeroInfo.isReport) {
        await startZeroReport(data);
      }
    }
    if (data.event === 'asyncTableDetailStart') {
      await startAsyncTableDetail();
    }

    if (data.event === 'baoBiaoDetailBack') {
      if (data.data.type === 'qysds') {
        window.sessionStorage.setItem('qysdsIsReport', 1);
      }
      window.location.href = window.location.href;
    }

    // 零申报结束返回事件
    if (data.event === 'zeroReportEnd') {
      // 同步申报表
      console.log(1111);
      window.postMessage(
        {
          event: 'asyncTableDetailRequest',
          data: 'tax'
        },
        '*'
      );
      // window.sessionStorage.setItem('zeroReport', 1);
      // window.postMessage(
      //   {
      //     event: 'asyncTableDetailStartCQ'
      //   },
      //   '*'
      // );
      // setTimeout(() => {
      //   // window.openWin('null', 'F251000200000176', '按期申报套餐', '102230');
      //   openFakeWin('null', 'F251000200000176', '按期申报套餐', '102230');
      // }, 1000);
    }
    if (data.event === 'asyncTableDetailRequestEnd') {
      window.postMessage(
        {
          event: 'clearZeroReport'
        },
        '*'
      );
      window.location.href = 'https://etax.chongqing.chinatax.gov.cn/sword?ctrl=WBLoginGdgjCtrl_openLayout3Win&isEnd=true';
      setTimeout(() => {
        // logout();
      }, 1000);
    }
  },
  false
);

function newFillInput({ saasData }, sheet) {
  let isYearReport = saasData.isYearReport;
  let ins = saasData.data.openParams.taxInfo.institution === '2013' ? 'xqykjzz' : 'qykjzz';
  let inputData;
  if (isYearReport && ins === 'xqykjzz') {
    inputData = saasData.data.openParams.inputData.data[sheet];
    let lastYearData = saasData.data.openParams.inputData.lastYearData[sheet];
    if (sheet === 'profit' || sheet === 'cash') {
      inputData = inputData.map((item, index) => {
        let obj = {};
        obj.colValue1 = item.colValue1;
        obj.colValue2 = lastYearData[index].colValue1;
        obj.reportItemName = lastYearData[index].reportItemName;
        return obj;
      });
    }
  } else {
    inputData = saasData.data.openParams.inputData.data[sheet];
  }
  if (['balance', 'profit', 'cash'].includes(sheet)) {
    try {
      let data = getinputData(inputData, ins, sheet, isYearReport);
      let contentIframe = document.querySelector('#allframe > div > div.x-tab-panel-body > iframe').contentDocument;
      let divs = contentIframe.querySelectorAll('body > div');
      let currentDivs = Array.from(divs).find(item => item.id.includes('table') && item.style.display !== 'none');
      let iframe = currentDivs.querySelector('iframe').contentDocument;
      console.log(data);
      data.forEach(({ key, value = 0 }) => {
        let input = iframe.querySelector(`#${key}`);
        input.set('value', value || 0)
          .set('realvalue', value || 0)
          .fireEvent('change');
      });
      window.postMessage(
        {
          event: 'fillInputDone',
          data: {
            message: '填报成功'
          }
        },
        '*'
      );
    } catch (e) {
      window.postMessage(
        {
          event: 'fillInputDone',
          data: {
            message: '填报失败'
          }
        },
        '*'
      );
    }
  }
}

function autoInputAccount({ companyInfo }) {
  if (!companyInfo || (!companyInfo.nationalTaxAccount && !companyInfo.nationalTaxId)) return;
  if ($('.alert_click_show').length === 0) return;
  if ($('.alert_click_show').attr('href') !== 'javascript:void(0)') return;
  let {
    nationalTaxId = '',
    nationalTaxAccount = '',
    nationalTaxUser = '',
    nationalTaxPass = '',
    taxStaffPhone = '',
  } = companyInfo;
  $('.alert_click_show').click();
  companyInfo = companyInfo || {};
  $('#shxydm_qy').val(nationalTaxId);
  $('#shxydm_qy').blur();
  // $('#username_qy').val(nationalTaxAccount || nationalTaxUser);
  $('#username_qy').val(nationalTaxAccount || nationalTaxUser);
  $('#username_qy').blur();
  $('#password_qy').val(nationalTaxPass);
  $('#password_qy').blur();
  setTimeout(() => {
    $('#sjhm_qy').val(taxStaffPhone);
  }, 1000)
}

/**
 * 调用接口获取公司信息
 */
function getNationData(taxType) {
  let taxInfo = {
    institution: '2013', // 国税对应制度 2007 | 2013
    nsrsbh: 'test', // 纳税人申报号
    nsrmc: 'test', // 纳税人名称（纳税公司）
    skssqq: '', // 税款所属期起
    skssqz: '', // 税款所属期止
    isZip: false,
    isHsqjSmall: false // 是否为小微企业汇算清缴
  };
  if (taxType == 'sds' || taxType == 'zzs') {
    window.postMessage(
      {
        event: 'backNationData',
        data: {
          taxInfo: taxInfo
        }
      },
      '*'
    );
    return;
  }
  if (taxType === 'hsqj') {
    if (isHsqjSmall()) taxInfo.isHsqjSmall = true;
    console.log(baseInfoCache);
    window.postMessage(
      {
        event: 'backNationData',
        data: {
          taxInfo: taxInfo
        }
      },
      '*'
    );
    return true;
  }
  let location = window.location;
  let port = location.port;
  let type = 'WLSB';
  if (port == '37013') {
    type = 'dswlsb';
  }

  let contentIframe = document.querySelector('#allframe > div > div.x-tab-panel-body > iframe');
  if (contentIframe) {
    contentIframe = contentIframe.contentDocument;
    let divs = contentIframe.querySelectorAll('body > div');
    let currentDivs = Array.from(divs).find(item => item.id.includes('table') && item.style.display !== 'none');
    if (currentDivs) {
      let iframe = currentDivs.querySelector('iframe').contentDocument;
      let textList = iframe.querySelectorAll("div[sword='SwordForm']");
      let is2007 = Array.from(textList).find(item => {
        let text = item.getAttribute('caption');
        console.log(text);
        return text.includes('适用未执行新金融准则、新收入准则和新租赁准则的一般企业') || text.includes('适用执行企业会计准则的一般企业');
      });
      if (is2007) {
        taxInfo.institution = '2007';
      }
    }
  }
  window.postMessage(
    {
      event: 'backNationData',
      data: {
        taxInfo: taxInfo
      }
    },
    '*'
  );
}

/**
 * 判断是否为小微企业 汇算清缴
 */
function isHsqjSmall() {
  const iframe = getHsqjIframe();
  if (iframe) {
    const title = iframe.contentWindow.document.querySelector('.table-title').innerText
      || '';
    return !title.includes('一般企业');
  }
  return false;
}

function getHsqjIframe() {
  // return $('body').find('.mini-panel iframe:visible')[0];
  return $('.mini-panel iframe')[0];
}
function fillHspj(inputData, sheet) {
  let { data } = inputData.saasData;
  Object.keys(data).forEach((item) => {
    let contents = $('div.mini-panel-viewport > div.mini-panel-body > iframe').contents();
    let input = contents.find(`#${item}`);
    input.focus();
    input.val(parseFloat(data[item]).toFixed(2));
    input.blur();
  });
}
async function fillInput({ saasData }) {
  let sheet = saasData.sheet;
  if (!$iframe) {
    let iframeD = document.querySelector('#ym-ml .ym-body iframe');
    $iframe = iframeD.contentDocument;
    if (!$iframe) {
      window.location.onload();
    } else {
      changeType();
    }
  }
  let tableType;
  let checkType = '《资产负债表（适用执行小企业会计准则的企业）》';
  const typeSign = $iframe.querySelector('input[name=SwordTreeJSON]');
  if (!typeSign) {
    checkType = typeSign.getAttribute('originvalue')
      || '《资产负债表（适用执行小企业会计准则的企业）》';
  }
  if (!namesKeys.includes(names[sheet].name)) {
    alert('填报报表与一键报税填报报表类型不匹配请核实');
    return;
  }
  let currentIframe;
  if (typeSign.getAttribute('realvalue')) {
    currentIframe = $iframe.getElementById(
      `table${typeSign.getAttribute('realvalue')}iframe`
    ).contentDocument;
  } else {
    currentIframe = $iframe.getElementById('table00iframe').contentDocument;
  }
  tableType = names[sheet].code;
  let message = '填报成功';
  try {
    let inputData = saasData.data;
    if (sheet == 'sds' || sheet == 'zzs') {
      // inputData = delSdsData(inputData.openParams.inputData.data.profit);
    }
    for (let key in inputData) {
      const input = currentIframe.getElementById(`${tableType}${key}`);
      input
        .set('value', inputData[key])
        .set('realvalue', inputData[key])
        .fireEvent('change');
    }
  } catch (e) {
    message = '填报失败' + e;
  }

  // todo finally
  window.postMessage(
    {
      event: 'fillInputDone',
      data: {
        message: message || '填报成功'
      }
    },
    '*'
  );
}
function url2json(url) {
  let index = -1,
    str = '',
    arr = [],
    length = 0,
    res = {};
  if (url.indexOf('?') !== -1) {
    index = url.indexOf('?');
    str = url.substring(index + 1);
    arr = str.split('&');
    length = arr.length;
    for (let i = 0; i < length - 1; i++) {
      res[arr[i].split('=')[0]] = arr[i].split('=')[1];
    }
  } else {
    res = {};
  }
  return res;
}


// 同步申报表 - 打开页面
if (
  window.location.href.includes(
    'etax.chongqing.chinatax.gov.cn/sword?ctrl=WBLoginGdgjCtrl_openLayout3Win'
  )
) {
  asyncOpenPage();
}
// 同步申报表 - 小规模增值税
if (
  window.location.href.includes(
    'https://etax.chongqing.chinatax.gov.cn:8001/WLSB/WLSBBS/TTAX_index.html?MODULE=TTAX_SB_JCSB.html'
  )
) {
  asyncTableDetail();
}
// 同步申报表 - 附件税
if (
  window.location.href.includes(
    'etax.chongqing.chinatax.gov.cn:6011/sword?ctrl=CX33SbxxcxCtrl_entry'
  )
) {
  asyncTableDetailFjs();
}
if (
  window.location.href.includes(
    'https://etax.chongqing.chinatax.gov.cn:6011/form.sword'
  )
) {
  asyncTableDetailFjsTable();
}
if (
  window.location.href.includes(
    'https://etax.chongqing.chinatax.gov.cn:8002/js3qbbcxtax/index.html'
  )
) {
  startAsyncTableDetail();
}
